package com.easylinkin.linkappapi.facerecognition.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.deviceattributestatus.entity.DeviceAttributeStatus;
import com.easylinkin.linkappapi.deviceattributestatus.service.DeviceAttributeStatusService;
import com.easylinkin.linkappapi.facerecognition.entity.FaceCamera;
import com.easylinkin.linkappapi.facerecognition.service.FaceCameraService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/camera")
public class FaceCameraController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private FaceCameraService faceCameraService;

    @Autowired
    private DeviceAttributeStatusService deviceAttributeStatusService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @PostMapping
    public RestMessage createFaceCamera(@Validated @RequestBody FaceCamera faceCamera) {

        if (faceCameraService.queryCameraWithPosition(faceCamera.getPosition()) != null) {
            return RestBuilders.failureBuilder().message("摄像头位置已存在").build();
        }

        if (faceCameraService.queryCameraWithDeviceCode(faceCamera.getDeviceCode()) != null) {
            return RestBuilders.failureBuilder().message("摄像头已绑定").build();
        }
        faceCamera.setTenantId(linkappUserContextProducer.getCurrent().getTenantId());
        boolean success = faceCameraService.save(faceCamera);
        if (!success) {
            return RestBuilders.failureBuilder().message("create face camera error").build();
        }
        return RestBuilders.successBuilder().build();
    }

    /**
     * 查询摄像头管理列表
     * */
    @PostMapping("/page")
    public RestMessage queryFaceCamera(@RequestBody RequestModel<FaceCamera> requestModel) {
        IPage<FaceCamera> record = faceCameraService.queryFaceCameras(requestModel.getPage(), requestModel.getCustomQueryParams());
        record.getRecords()
                .forEach(camera -> {
                    List<DeviceAttributeStatus> latestDeviceAttributeStatusList = deviceAttributeStatusService.getLatestDeviceAttributeStatusList(camera.getDeviceCode(),null);
                    if (latestDeviceAttributeStatusList != null) {
                        String mediaUrl = latestDeviceAttributeStatusList.
                                stream().map(DeviceAttributeStatus::getPropValue)
                                .filter(propValue -> isFlvMediaUrl(propValue.toLowerCase()))
                                .findAny()
                                .orElse("");

                        camera.setFlvMediaUrl(mediaUrl);
                    }
                });
        return RestBuilders.successBuilder().data(record).build();
    }

    @GetMapping("/all")
    public RestMessage queryAllFaceCamera() {

        return RestBuilders.successBuilder().data(faceCameraService.queryAllFaceCamera()).build();
    }

    private boolean isFlvMediaUrl(String msg) {
        return msg.startsWith("http") && msg.endsWith("flv");
    }

    @PostMapping("/update")
    public RestMessage updateFaceCamera(@Validated @RequestBody FaceCamera faceCamera) {

        if (faceCamera.getId() == null) {
            return RestBuilders.failureBuilder().message("摄像头ID为空").build();
        }

        if (faceCameraService.getById(faceCamera.getId()) == null) {
            return RestBuilders.failureBuilder().message("摄像头为空").build();
        }

        FaceCamera faceCamera1 = faceCameraService.queryCameraWithPosition(faceCamera.getPosition());
        if (faceCamera1 != null && !faceCamera1.getId().equals(faceCamera.getId())) {
            return RestBuilders.failureBuilder().message("摄像头位置已存在").build();
        }

        FaceCamera faceCamera2 = faceCameraService.queryCameraWithDeviceCode(faceCamera.getDeviceCode());
        if ( faceCamera2 != null && !faceCamera2.getId().equals(faceCamera.getId())) {
            return RestBuilders.failureBuilder().message("摄像头已绑定").build();
        }

        boolean success = faceCameraService.updateById(faceCamera);
        if (!success) {
            return RestBuilders.failureBuilder().message("create face camera error").build();
        }
        return RestBuilders.successBuilder().build();
    }

    @PostMapping("/batch/delete")
    public RestMessage batchDeleteCamera(@RequestParam("ids") String ids) {
        if (ids == null || ids.isEmpty()) {
            return RestBuilders.successBuilder().build();
        }

        List<String> cameraIds = Arrays.asList(ids.split(","));

        String currentTenantId = linkappUserContextProducer.getCurrent().getTenantId();
        List<Long> deniedIds = faceCameraService.listByIds(cameraIds).stream()
                .filter(r -> !r.getTenantId().equalsIgnoreCase(currentTenantId))
                .mapToLong(FaceCamera::getId)
                .boxed()
                .collect(Collectors.toList());

        if (deniedIds.size() != 0) {
            return RestBuilders.failureBuilder().message("无权删除").data(deniedIds).build();
        }

        if (!faceCameraService.removeByIds(cameraIds)) {
            return RestBuilders.failureBuilder().message("批量删除摄像头失败").build();
        }

        return RestBuilders.successBuilder().build();
    }

    @GetMapping("/device")
    public RestMessage queryCameraDevice() {

        return RestBuilders.successBuilder().data(deviceService.selectCameraDevices(linkappUserContextProducer.getCurrent().getTenantId())).build();
    }
}
